package com.unlcn.ils.erpInterfaces.service.buss.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.unlcn.ils.erpInterfaces.dao.mapper.SmvehiclequeueMapper;
import com.unlcn.ils.erpInterfaces.dao.model.LisaRequestLog;
import com.unlcn.ils.erpInterfaces.dao.model.Smfleet;
import com.unlcn.ils.erpInterfaces.dao.model.Smvehicle;
import com.unlcn.ils.erpInterfaces.dao.model.Smvehiclequeue;
import com.unlcn.ils.erpInterfaces.dao.model.bo.VehicleQueueBO;
import com.unlcn.ils.erpInterfaces.service.buss.*;
import com.unlcn.ils.erpInterfaces.service.util.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * SMVEHICLEQUEUE 报班表  服务实现类
 * </p>
 *
 * @author liangpeng
 * @since 2018-06-14
 */
@Service
public class SmvehiclequeueServiceImpl extends ServiceImpl<SmvehiclequeueMapper, Smvehiclequeue> implements ISmvehiclequeueService {

    @Autowired
    private SmvehiclequeueMapper smvehiclequeueMapper;

    @Autowired
    private ISmvehicleService smvehicleService;

    @Autowired
    private ISmdriverService smdriverService;

    @Autowired
    private ISmfleetService smfleetService;

    @Autowired
    private ILisaRequestLogService lisaRequestLogService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long vehicleQueue(VehicleQueueBO vehicleQueueBO) {

        // 检查数据
        checkData(vehicleQueueBO);

        // 查询车辆信息
        Wrapper<Smvehicle> smvehicleWrapper = new EntityWrapper<>();
        smvehicleWrapper.eq("VCLICENSE", vehicleQueueBO.getLicense());
        List<Smvehicle> smvehicleList = smvehicleService.selectList(smvehicleWrapper);
        if (CollectionUtils.isEmpty(smvehicleList)) {
            throw new BaseException("车辆无效，如车牌无误，请联系运力管理在ERP手工维护");
        }
        Smvehicle smvehicle = smvehicleList.get(0);
        if (smvehicle.getIfleetid() == null) {
            throw new BaseException("ERP车辆" + smvehicle.getVcvehicleno() + "无车队信息,请联系管理员");
        }
        //fix  增加erp车队和运力平台的校验
        Smfleet smfleet = smfleetService.selectById(smvehicle.getIfleetid());
        if (smfleet != null
                && !StringUtils.isEmpty(smfleet.getVcfleetname())
                && !smfleet.getVcfleetname().equals(vehicleQueueBO.getFleetName())) {
            throw new BaseException("报班无效,ERP车队信息" + smfleet.getVcfleetname()
                    + "与运力平台车队" + vehicleQueueBO.getFleetName() + "不符,请联系管理员调整");
        }

//        // 查询车辆的主驾司机状态是否有效
//        Long drierId = smvehicle.getIdriverid();
//        Wrapper<Smdriver> smdriverWrapper = new EntityWrapper<>();
//        smdriverWrapper.eq("ILINEID", drierId);
//        List<Smdriver> smdriverList = smdriverService.selectList(smdriverWrapper);
//        if (CollectionUtils.isEmpty(smdriverList)) {
//            throw new BaseException("无法找到车辆的主驾司机，请联系运力管理在ERP手工维护");
//        }
//        Smdriver smdriver = smdriverList.get(0);
//        if (smdriver.getBactive() == 0) {
//            throw new BaseException("车辆的主驾司机属于无效状态");
//        }

//        // 查询车辆的副驾司机状态是否有效
//        Long drierId2 = smvehicle.getIdriverid();
//        Wrapper<Smdriver> smdriverWrapper2 = new EntityWrapper<>();
//        smdriverWrapper2.eq("ILINEID", drierId2);
//        List<Smdriver> smdriverList2 = smdriverService.selectList(smdriverWrapper2);
//        if (CollectionUtils.isEmpty(smdriverList2)) {
//            throw new BaseException("无法找到车辆的副驾司机，请联系运力管理在ERP手工维护");
//        }
//        Smdriver smdriver2 = smdriverList2.get(0);
//        if (smdriver2.getBactive() == 0) {
//            throw new BaseException("车辆的副驾司机属于无效状态");
//        }

//        // 超过三天未正常定位的车辆，不允许报班
//        Date dtlocationdate = smvehicle.getDtlocationdate();
//        Integer days = null;
//        if (dtlocationdate == null) {
//            days = 30;
//        } else {
//            Date nowDate = new Date();
//            DateTime dt1 = new DateTime(dtlocationdate);
//            DateTime dt2 = new DateTime(nowDate);
//            days = Days.daysBetween(dt1, dt2).getDays();
//        }
//        if (days > 3) {
//            throw new BaseException("该车已经［" + days + "］天未正常定位，不允许报班");
//        }


        // 查看车辆是否存在未消耗的报班
        Wrapper<Smvehiclequeue> smvehiclequeueWrapper = new EntityWrapper<>();
        smvehiclequeueWrapper.eq("ivehicleid", smvehicle.getIlineid());
        smvehiclequeueWrapper.eq("istatus", 0);
        Integer actives[] = {0, 1};
        smvehiclequeueWrapper.in("bactive", actives);
        List<Smvehiclequeue> smvehiclequeueList = smvehiclequeueMapper.selectList(smvehiclequeueWrapper);
        if (!CollectionUtils.isEmpty(smvehiclequeueList)) {
            throw new BaseException("车辆[" + vehicleQueueBO.getLicense() + "]已存在未消耗的报班");
        }

        Smvehiclequeue insertVehiclequeue = new Smvehiclequeue();
        // 登记人
        insertVehiclequeue.setVcuserno(vehicleQueueBO.getDriverName());
        // 登记时间
        insertVehiclequeue.setDtdate(new Date());
        // 申请人
        insertVehiclequeue.setVcedituserno(vehicleQueueBO.getDriverName());
        // 申请时间
        insertVehiclequeue.setDteditdate(new Date());
        // 登记时的位置
        insertVehiclequeue.setVclocation(vehicleQueueBO.getLocation());
        // 车辆 id
        insertVehiclequeue.setIvehicleid(smvehicle.getIlineid());
        // 车辆所属车队 id
        insertVehiclequeue.setIfleetid(smvehicle.getIfleetid());

        // 报到城市
        insertVehiclequeue.setVccomecityname(vehicleQueueBO.getDepartRegion());

        //预计发运方向
        insertVehiclequeue.setVcshipmemo(vehicleQueueBO.getDestRegion());

        //预计装载数量
        insertVehiclequeue.setDcqty(Long.parseLong(StringUtils.isEmpty(vehicleQueueBO.getAmtExp()) ? "0" : vehicleQueueBO.getAmtExp()));

        //预计到达时间
        insertVehiclequeue.setDtcomedate(vehicleQueueBO.getGmtExpLoad());

        //可用时间
        insertVehiclequeue.setDtactiondate(vehicleQueueBO.getGmtExpLoad());

        //设置有效
        insertVehiclequeue.setBactive(1L);

        //经度
        insertVehiclequeue.setVclongitude(vehicleQueueBO.getCheckinLongtitude().toString());

        //纬度
        insertVehiclequeue.setVclatitude(vehicleQueueBO.getCheckinLatitude().toString());

        // 插入报班信息
        insertVehiclequeue.setIlineid(smvehiclequeueMapper.getNextIlineid());

        smvehiclequeueMapper.insert(insertVehiclequeue);

        return insertVehiclequeue.getIlineid();
    }

    @Override
    public void checkData(VehicleQueueBO vehicleQueueBO) {

        if (StringUtils.isEmpty(vehicleQueueBO.getDriverQueueId())) {
            throw new BaseException("司机公众号报班 id 为空");
        }

        if (StringUtils.isEmpty(vehicleQueueBO.getLicense())) {
            throw new BaseException("车牌号为空");
        }

        if (StringUtils.isEmpty(vehicleQueueBO.getDriverName())) {
            throw new BaseException("司机名称为空");
        }

        if (StringUtils.isEmpty(vehicleQueueBO.getDepartRegion())) {
            throw new BaseException("报到城市为空");
        }

        if (StringUtils.isEmpty(vehicleQueueBO.getDestRegion())) {
            throw new BaseException("预计发运方向为空");
        }

        if (Objects.isNull(vehicleQueueBO.getGmtExpLoad())) {
            throw new BaseException("预计到达时间为空");
        }

        if (StringUtils.isEmpty(vehicleQueueBO.getLocation())) {
            throw new BaseException("报班时具体位置为空");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean cancelVehicleQueue(Long driverQueueId) {
        Wrapper<LisaRequestLog> ew = new EntityWrapper<>();
        ew.eq("DRIVER_QUEUE_ID", driverQueueId).eq("IS_SUCCESS", 1).eq("url", "/queue/vehicleQueue");

        LisaRequestLog lisaRequestLog = lisaRequestLogService.selectOne(ew);
        if (Objects.isNull(lisaRequestLog)) {
            throw new BaseException("没有报班可以进行取消");
        }
        //erp中的报班号
        Long erpQueueId = lisaRequestLog.getErpQueueId();
        if (Objects.isNull(erpQueueId)) {
            throw new BaseException("报班编号不存在");
        }

        Smvehiclequeue smvehiclequeue = this.selectById(erpQueueId);
        if (Objects.isNull(smvehiclequeue)) {
            throw new BaseException("报班信息不存在");
        }

        if (smvehiclequeue.getBactive().equals(2L) && smvehiclequeue.getIstatus().equals(2)) {
            throw new BaseException("该报班信息已经被取消");
        }

        smvehiclequeue.setBactive(2L);
        smvehiclequeue.setIstatus(2);
        int intCount = smvehiclequeueMapper.updateById(smvehiclequeue);
        return intCount > 0;

    }
}
